import React, {Component} from 'react';
import {
    Dimensions,
    FlatList,
    Image,
    PixelRatio,
    StyleSheet,
    Text,
    TouchableHighlight,
    View,
    TouchableOpacity,
    ScrollView
} from 'react-native';


import LinkButton from './LinkButton'
import {
    Actions
} from 'react-native-router-flux';

import UserInfoUtil from './UserInfoUtil';
import {ListRow, SearchInput,Drawer,Theme} from 'teaset';
import Config from './common/Config'
import Utils from './Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
import TitleBar from './views/TitleBar';
import SideBar from './views/SideBar';
import CommonTitleBar from './views/CommonTitleBar';
import CommonLoadingView from './views/CommonLoadingView';
import StorageUtil from './views/StorageUtil';
import ListItemDivider from './views/ListItemDivider';
export default class ContactsScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loadingState: 1,
            contactData: null,
        }
    }

    getContacts() {
        var url = "http://rnwechat.applinzi.com/friends"; // 新接口
        fetch(url).then((res) => res.json())
            .then((json) => {
                UserInfoUtil.setUserInfo(json);
                this.setState({
                    loadingState: 2,
                    contactData: json
                })
            })
    }

    render() {
        switch (this.state.loadingState) {
            case 1:
                this.getContacts();
                return this.renderLoadingView();
            case 2:
                return this.renderSuccessView();
            case 3:
                return this.renderErrorView();
            default:
        }
    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                <TitleBar nav={this.props.navigation}/>
                <View style={styles.content}>
                    <CommonLoadingView hintText={"正在获取联系人数据..."}/>
                </View>
            </View>
        );
    }

    renderErrorView() {
        return (
            <View style={{justifyContent: 'center', alignItems: 'center', flex: 1, flexDirection: 'column'}}>
                <Text style={{fontSize: 16, color: '#000000'}}>加载数据出错！</Text>
            </View>
        );
    }

    renderSuccessView() {
        var listData = [];
        var headerListData = [];
        var headerImages = [ ImageUtil.NewFriend, ImageUtil.GroupChat];
        var headerTitles = ['新的朋友', '发起群聊'];
        var index = 0;
        for (var i = 0; i < headerTitles.length; i++) {
            headerListData.push({
                key: index++,
                title: headerTitles[i],
                nick: '',
                icon: headerImages[i],
                sectionStart: false,
            });
        }
        var contacts = this.state.contactData;
        for (let i = 0; i < contacts.length; i++) {
            // var pinyin = PinyinUtil.getFullChars(contacts[i].name);
            var pinyin = contacts[i].pinyin.toUpperCase();
            var firstLetter = pinyin.substring(0, 1);
            if (firstLetter < 'A' || firstLetter > 'Z') {
                firstLetter = '#';
            }
            let icon = ImageUtil.Search;
            if (!Utils.isEmpty(contacts[i].avatar)) {
                icon = {uri: contacts[i].avatar};
            }
            listData.push({
                key: index++,
                icon: icon,
                title: contacts[i].name,
                nick: contacts[i].nick,
                pinyin: pinyin,
                firstLetter: firstLetter,
                sectionStart: false,
            })
        }
        // 按拼音排序
        listData.sort(function (a, b) {
            if (a.pinyin === undefined || b.pinyin === undefined) {
                return 1;
            }
            if (a.pinyin > b.pinyin) {
                return 1;
            }
            if (a.pinyin < b.pinyin) {
                return -1;
            }
            return 0;
        });
        listData = headerListData.concat(listData);
        // 根据首字母分区
        for (var i = 0; i < listData.length; i++) {
            var obj = listData[i];
            if (obj.pinyin === undefined) {
                continue;
            }
            if (i > 0 && i < listData.length) {
                var preObj = listData[i - 1];
                if (preObj.pinyin === undefined && obj.pinyin !== undefined) {
                    obj.sectionStart = true;
                } else if (preObj.pinyin !== undefined && obj.pinyin !== undefined && preObj.firstLetter !== obj.firstLetter) {
                    obj.sectionStart = true;
                }
            }
        }
        this.listData = listData;
        return (
            <View style={styles.container}>
                {alert(JSON.stringify(listData[60]))}
                <TitleBar/>
                <View style={styles.content}>
                    <FlatList
                        ref={'list'}
                        data={listData}
                        renderItem={this._renderItem}
                        ListHeaderComponent={this.ListHeader}
                        getItemLayout={this._getItemLayout}
                    />
                    {/*<SideBar onLetterSelectedListener={this.onSideBarSelected.bind(this)}/>*/}
                </View>
                <View style={styles.divider}/>
            </View>
        );
    }

    ListHeader=()=>{
        return(
            <View>
                <View style={{justifyContent:'center',alignItems:'center'}}>
                    <SearchInput style={styles.searchInput} placeholder='搜索' clearButtonMode='while-editing'/>
                </View>
                <TouchableOpacity style={styles.labelView}>
                    <Image
                        style={styles.labelImg}
                        source={ImageUtil.CustomerService}/>
                    <Text style={styles.labelMsg}>信用客服0574</Text>
                </TouchableOpacity>
                <View style={{height:12,width:width}}/>
            </View>
        )
    };

    _getItemLayout = (data, index) => {
        let len = data.sectionStart ? (58) : (51);
        let dividerHeight = 1 / PixelRatio.get();
        return {
            length: len,
            offset: (len + dividerHeight) * index,
            index
        };
    }

    onSideBarSelected(letter) {
        if (this.listData) {
            for (let i = 0; i < this.listData.length; i++) {
                let item = this.listData[i];
                if (item.firstLetter == letter && item.sectionStart) {
                    Toast.message(letter);
                    this.refs.list.scrollToIndex({viewPosition: 0, index: i});
                    break;
                }
            }
        }
    }

    onListItemClick(item) {
        let index = item.item.key;
        if (index == 0) {
            // 新的朋友
            this.props.navigation.navigate('NewFriend', {title: '新的朋友', data: item.item})
        } else if (index >= 1 && index <= 3) {
            Toast.message('功能未实现');
        } else {
            this.props.navigation.navigate('ContactDetail', {title: '详细资料', data: item.item});
        }
    }

    _renderItem = (item) => {
        var section = [];
        if (item.item.sectionStart) {
            section.push(<View key={"section" + item.item.key}
                               style={{borderBottomWidth:1,  borderColor:'#e3e3e4'}}>
                <Text style={listItemStyle.sectionView}>{item.item.firstLetter}</Text>
            </View>);
        }
        return (
            <View >
                {section}
                <TouchableHighlight
                    onPress={() => {
                    this.onListItemClick(item)
                }}>
                    <View style={listItemStyle.container} key={item.item.key}>
                        <View style={{width:width-30,borderColor:'#e3e3e4', borderBottomWidth:1,marginLeft:15,flexDirection:'row', alignItems: 'center',}}>
                            <Image style={listItemStyle.image} source={item.item.icon}/>
                            <Text style={listItemStyle.itemText}>{item.item.title}</Text>
                            <Text style={listItemStyle.subText}>{Utils.isEmpty(item.item.nick)}</Text>
                        </View>
                    </View>
                </TouchableHighlight>
                <View style={{width: width-30, height: 1 / PixelRatio.get(), backgroundColor: '#e3e3e4',marginLeft:15}}/>
            </View>
        );
    }
}

const listItemStyle = StyleSheet.create({
    container: {
        width: width,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#ffffff',

    },
    image: {
        marginRight: 19,
        marginTop: 5,
        marginBottom: 5,
        width: 35,
        height: 35,
    },
    itemText: {
        fontSize: 15,
        color: '#000000'
    },
    subText: {
        fontSize: 15,
        color: '#999999'
    },
    sectionView: {
        width: width,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        marginLeft: 15,
        color: '#000000',
    }
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor:'#f0f0f0'
    },
    divider: {
        width: width,
        height: 1 / PixelRatio.get(),
        backgroundColor: '#D3D3D3'
    },
    content: {
        flex: 1,
        width: width,
        flexDirection: 'row',
        backgroundColor: '#f0f0f0'
    },
    tabBarIcon: {
        width: 24,
        height: 24,
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12,
        flexDirection:'row',
        alignItems:'center'
    },
    labelChangeView:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12,
        alignItems:'center'
    },
    labelImg:{
        marginLeft:15,
        width:30,
        height:30,
        borderRadius:5
    },
    labelMsg:{
        marginLeft:19,
        fontSize:14,
        color:'#000000'
    },
    labelCategorizeView:{
        borderBottomWidth:1,
        borderColor:'#e3e3e4',
        width:width-30,
        flexDirection:'row',
        alignItems:'center',
        height:45
    },
    labelCategorizeImg:{
        width:30,
        height:30,
        borderRadius:5
    },
    labelCategorizeViewBottom:{
        width:width-30,
        flexDirection:'row',
        alignItems:'center',
        height:45
    },
    iconView:{
        height:17,
        justifyContent:'center',
        width:width,
    },
    iconMsg:{
        fontSize:14,
        color:'#000000',
        marginLeft:15
    },
    labelChange:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        alignItems:'center'
    },
    searchInput:{
        width:width-30,
        height:29,
        borderWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12
    },
});

